package com.jy.appmarket.notification;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.AppUpdateActivity;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.model.AppUpdateModel;
import com.jy.appmarket.utils.Prefs;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.RemoteViews;

/*
 * 
 * 手机安装的app更新通知
 */
public class AppUpdateNotification {

	private static int APP_UPDATE_NOTIFICATION_ID = 2000;

	/*
	 * 根据数据库判断有需要更新的apk，并且一天只发送两次，上午[10-12]点，下午一次[19-21]点各只发送一次
	 */
	private static boolean isShowTime(final Context context) {

		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
		String date = dateFormat.format(calendar.getTime());

		if (hour >= 12 && hour <= 14) {
			if (date.equals(Prefs.getAppUpdateNotificationNoon(context))) {
				return false;
			} else {
				Prefs.saveAppUpdateNotificationNoon(context, date);
				return true;
			}
		}
		if (hour >= 19 && hour <= 21) {
			if (date.equals(Prefs.getAppUpdateNotificationNight(context))) {
				return false;
			} else {
				Prefs.saveAppUpdateNotificationNight(context, date);
				return true;
			}
		}
		return false;
	}

	private static boolean hasAppNeedUpdate(final Context context) {
		AppUpdateDatabase localDatabase = AppUpdateDatabase.getInstance(context);
		localDatabase.correctAppUpdatesDatas(context);
		return localDatabase.getCount(false) > 0;
	}

	private static void sendAppUpdateNotification(final Context context) {
		AppUpdateDatabase localDatabase = AppUpdateDatabase.getInstance(context);
		RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appupdate_notificationi_layout);

		List<AppUpdateModel> appUpdateModels = localDatabase.getAllUpdatesOrderBy(AppUpdateDatabase.COL_LASTMODIFIED,
				true, false);
		int icons[] = new int[5];
		icons[0] = R.id.appupdate_notification_icon1;
		icons[1] = R.id.appupdate_notification_icon2;
		icons[2] = R.id.appupdate_notification_icon3;
		icons[3] = R.id.appupdate_notification_icon4;
		icons[4] = R.id.appupdate_notification_icon5;
		int maxIcon = appUpdateModels.size() > 5 ? 5 : appUpdateModels.size();
		rv.setTextViewText(R.id.appupdate_notification_title_tv, "您有" + appUpdateModels.size() + "款软件可升级!");
		for (int i = 0; i < 5; i++) {
			if (i < maxIcon) {
				rv.setViewVisibility(icons[i], View.VISIBLE);
				rv.setImageViewBitmap(icons[i],
						ImageLoader.getInstance().loadImageSync(appUpdateModels.get(i).getIconPath()));
			} else {
				rv.setViewVisibility(icons[i], View.GONE);
			}
		}

		NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification();
		notification.contentView = rv;

		Intent intent = new Intent(context, AppUpdateActivity.class);
		intent.putExtra("from", AppUpdateNotification.class.getName());
		PendingIntent pi = PendingIntent.getActivity(context, String.valueOf(System.currentTimeMillis()).hashCode(),
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.icon = R.drawable.ic_launcher;
		notification.defaults = Notification.DEFAULT_ALL;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.contentIntent = pi;
		notification.deleteIntent = PendingIntent.getBroadcast(context, 0,
				new Intent("com.jy.appmarket.ACTION.deleteupdatenotification"), PendingIntent.FLAG_UPDATE_CURRENT);
		notiManager.notify(APP_UPDATE_NOTIFICATION_ID, notification);
		AppMarketApplication.appUpdateNotificationShowing = true;
	}

	public static void showAppUpdateNotification(final Context context) {
		if (context == null) {
			return;
		}
		if (hasAppNeedUpdate(context) && isShowTime(context)) {
			Runnable r = new Runnable() {
				@Override
				public void run() {
					sendAppUpdateNotification(context);
				}
			};
			new Thread(r).start();
		}
	}

	public static void showAppUpdateNotificationImmediately(final Context context) {
		if (hasAppNeedUpdate(context)) {
			Runnable r = new Runnable() {
				@Override
				public void run() {
					sendAppUpdateNotification(context);
				}
			};
			new Thread(r).start();
		}
	}
}
